﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;

namespace TireService.Business.Portal.CustomerView
{
    public partial class CustomerData : System.Web.UI.Page
    {
        #region Public Properties

        public int CustomerId
        {
            get
            {
                if (ViewState["_customerid"] != null)
                    return (int)ViewState["_customerid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_customerid"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // TEST value
            //Session["CustomerId"] = "10000";

            if (Page.IsPostBack != true)
            {
                // Get data for dropdownlists
                ddlCountry.DataSource = db.GetCountries();
                ddlCountry.ValueField = "CountryId";
                ddlCountry.TextField = "CountryName";
                ddlCountry.DataBind();

                // Get customer id
                try
                {
                    // Get customer Id and save to propertie
                    if (Request.QueryString["CustomerId"] != null)
                    {
                        this.CustomerId = Convert.ToInt32(Request.QueryString["CustomerId"]);
                    }
                    else
                    {
                        this.CustomerId = Convert.ToInt32(Session["CustomerId"]);
                    }

                    if (this.CustomerId != 0)
                    {
                        // Check that customer has access to Customer
                        if (this.CustomerId == Convert.ToInt32(Session["CustomerId"]))
                        {
                            //// Load customer data
                            //LoadCustomer(db, this.CustomerId);
                        }
                        else
                        {
                            if (db.ValidateParentCustomerAccess(this.CustomerId, Convert.ToInt32(Session["CustomerId"])))
                            {
                                // Load customer data
                                LoadCustomer(db, this.CustomerId);
                            }
                            else
                            {
                                throw new ArgumentException("Kunde har ikke adgang til underafdeling/kunde.");
                            }
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Kunde ikke fundet.");
                    }
                }
                catch (Exception)
                {
                    // Nothing - invalid customerid, redirect customer to start page
                    Response.Redirect("~/Portal/Index.aspx");
                }
            }

            // Load customer data
            LoadCustomer(db, this.CustomerId);

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that load customer and change UI
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="CustomerId">Id for customer to load</param>
        protected void LoadCustomer(TireServiceDB db, int CustomerId)
        {
            // Set page propertie
            this.CustomerId = CustomerId;

            if (CustomerId != 0)
            {
                // Bind item data to editform
                Customer customer = new Customer();
                customer = db.GetCustomer(CustomerId);

                if (customer != null)
                {
                    // Set form fields
                    // Customer info
                    lblCustomerNumberValue.Text = customer.CustomerId.ToString();

                    if (customer.ParentCustomerId != null) lblParentCompanyValue.Text = db.GetCustomerCompanyName(this.CustomerId);
                    cbParentPayInvoice.Checked = customer.ParentPayInvoice;
                    txtCompanyName.Text = customer.CompanyName;
                    txtCompanyNumber.Text = customer.CompanyNumber;

                    txtName.Text = customer.Name;
                    txtAddress.Text = customer.Address;
                    txtZipCode.Text = customer.ZipCode;
                    txtCity.Text = customer.City;
                    ddlCountry.Items.FindByValue(Convert.ToString(customer.CountryId)).Selected = true;
                    txtSecondaryAddress.Text = customer.SecondaryAddress;
                    txtSecondaryZipCode.Text = customer.SecondaryZipCode;
                    txtSecondaryCity.Text = customer.SecondaryCity;
                    txtPhone1.Text = customer.Phone1;
                    ddlPhone1Type.Items.FindByValue(Convert.ToString(customer.Phone1Type)).Selected = true;
                    if (customer.Phone2 != null) txtPhone2.Text = customer.Phone2;
                    if (customer.Phone2 != null) ddlPhone2Type.Items.FindByValue(Convert.ToString(customer.Phone2Type)).Selected = true;
                    txtEmail.Text = customer.Email;
                    rbPrimaryAddressTimeInterval.Value = Convert.ToBoolean(customer.OnPrimaryAddressInPrimeTime);

                    // Load subdepartments
                    gvCustomer.DataSource = db.GetCustomersForParentCustomerView(customer.CustomerId);
                    gvCustomer.DataBind();
                }
            }
            else
            {
                // Nothing - invalid customerid, redirect customer to start page
                Response.Redirect("~/Portal/Index.aspx");
            }
        }

        /// <summary>
        /// Button function that saves and updates customer data
        /// </summary>
        protected void btnSaveCustomer_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.CustomerId == 0)
                {
                    // Nothing - invalid customerid, redirect customer to start page
                    Response.Redirect("~/Portal/Index.aspx");
                }

                TireServiceDB db = new TireServiceDB();

                // Update customer
                Customer customer = db.GetCustomer(this.CustomerId);

                CustomerBLL customerBLL = new CustomerBLL();
                customerBLL.UpdateCustomer(
                                            db,
                                            customer,
                                            this.CustomerId,
                                            (customer.ParentCustomerId != null),
                                            customer.ParentCustomerId,
                                            customer.ParentPayInvoice,
                                            customer.IsCompany,
                                            txtCompanyName.Text,
                                            txtCompanyNumber.Text,
                                            txtName.Text,
                                            txtAddress.Text,
                                            txtZipCode.Text,
                                            txtCity.Text,
                                            Convert.ToInt32(ddlCountry.SelectedItem.Value),
                                            txtSecondaryAddress.Text,
                                            txtSecondaryZipCode.Text,
                                            txtSecondaryCity.Text,
                                            txtPhone1.Text,
                                            Convert.ToInt32(ddlPhone1Type.SelectedItem.Value),
                                            txtPhone2.Text,
                                            Convert.ToInt32(ddlPhone2Type.SelectedItem.Value),
                                            txtEmail.Text,
                                            Convert.ToBoolean(rbPrimaryAddressTimeInterval.SelectedItem.Value),
                                            customer.SyncToEconomic,
                                            false
                                        );

                //// Submit changes to database
                //db.SubmitChanges();

                // Show message to user
                lMessage.Text = "Kundedata blev opdateret";

                // Dispose database connection
                db.Dispose();
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }

        }

        #region GridView Functions

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvCustomer_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn Type: Show country name
            if (e.Column.FieldName == "CountryName")
            {
                // Get countryid
                int countryid = Convert.ToInt32(e.GetListSourceFieldValue("CountryId"));

                TireServiceDB db = new TireServiceDB();

                // Change field value
                e.Value = db.GetCountryName(countryid);

                db.Dispose();
            }
        }

        #endregion
    }
}